package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserEmployeeMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserEmployeeService;
import com.sky.utils.HttpClientUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * @Classname UserEmployeeServiceImpl
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/7/3 11:34
 * @Created by Ren
 */
@Service
public class UserEmployeeServiceImpl implements UserEmployeeService {

    private static final String URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Resource
    private WeChatProperties weChatProperties;
    @Resource
    private UserEmployeeMapper userEmployeeMapper;

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {

        //向微信服务器发送请求,得到openid
        String openid = getOpenId(userLoginDTO);

        if (openid == null) {
            //说明小程序给的 code 过期或者错误,直接报异常
            throw new RuntimeException(MessageConstant.LOGIN_FAILED);
        }

        //判断是否是新用户
        User user = userEmployeeMapper.selectByOpenId(openid);
        if (user == null) {
            //说明是新用户 插入
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userEmployeeMapper.insertUser(user);
        }

        //说明不是新用户
        return user;

    }

    private String getOpenId(UserLoginDTO userLoginDTO) {
        HashMap<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", userLoginDTO.getCode());
        map.put("grant_type", "authorization_code");
        String result = HttpClientUtil.doGet(URL, map);

        //将result返回的json格式
        JSONObject jsonObject = JSONObject.parseObject(result);
        String openid = jsonObject.getString("openid");
        return openid;
    }

    private User getById(Long id){
        User user = userEmployeeMapper.getById(id);
        return user;
    }
}
